package com.mmall.seckill.common.filter;

import com.mmall.seckill.common.redis.RedisService;
import com.mmall.seckill.common.redis.keyCode.SeckillUserKey;
import com.mmall.seckill.domain.SeckillUser;
import com.mmall.seckill.util.CookieUtil;
import com.mmall.seckill.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 实现ServletException接口重置session有效期
 * Created by megan on 2018/1/2.
 */
public class SessionExpireFilter implements Filter {
    @Resource
    private RedisService redisService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);

        if(StringUtils.isNotEmpty(loginToken)){
            //判断loginToken是否为null或者为""字符串,如果不为空的话,符合条件,继续拿user信息
            String userJsonStr = redisService.get(SeckillUserKey.token,loginToken);
            SeckillUser user = JsonUtil.string2Obj(userJsonStr,SeckillUser.class);

            if(user != null){
                //如果user不为空,则重置session的时间,即调用expire命令
                redisService.expire(SeckillUserKey.token,loginToken, SeckillUserKey.token.expireSeconds());
                CookieUtil.writrLoginTokenEx(httpServletResponse,loginToken, SeckillUserKey.token.expireSeconds());
            }
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
